package com.example.qxfw.mongodb.hy.controller;

import com.example.qxfw.common.SysResult;
import com.example.qxfw.mongodb.hy.entity.HyImageFile;
import com.example.qxfw.mongodb.hy.service.HyImageFileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;

@Api(tags = "Mongo服务库-图片文件")
@RestController
@CrossOrigin
@RequestMapping("/hy/imageFile")
public class HyImageFileController {

    @Autowired
    private HyImageFileService imageFileService;

    @ApiOperation("获取图片文件")
    @GetMapping("/getByIdAndTableName")
    public SysResult getImageFile(String id, String tableName, HttpServletResponse response) throws IOException {
        HyImageFile imageFile = imageFileService.getByParam(id, tableName);
        if(imageFile==null||imageFile.getName()==null){
            return SysResult.fail("图片文件不存在");
        }
        InputStream inputStream = new ByteArrayInputStream(imageFile.getData());

        response.setContentType("application/octet-stream");
        response.addHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(imageFile.getName()+".png", "UTF-8"));
        ServletOutputStream outputStream = response.getOutputStream();
        byte[] b = new byte[1024];
        int len;
        while ((len = inputStream.read(b)) > 0) {
            outputStream.write(b, 0, len);
        }
        inputStream.close();
        return null;
    }

    @ApiOperation("获取图片文件")
    @GetMapping("/getById")
    public void getImageFile(String id, HttpServletResponse response) throws IOException {
        HyImageFile imageFile = imageFileService.getById(id);
        InputStream inputStream = new ByteArrayInputStream(imageFile.getData());
        response.setContentType("application/octet-stream");
        response.addHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode("图片.png", "UTF-8"));
        ServletOutputStream outputStream = response.getOutputStream();
        byte[] b = new byte[1024];
        int len;
        while ((len = inputStream.read(b)) > 0) {
            outputStream.write(b, 0, len);
        }
        inputStream.close();
    }
}
